//
//  NMPODataSaveManager.swift
//  NMPO
//
//  Created by PowerfullClean on 2023/11/1.
//

import UIKit
import CoreData
import Disk

let nmpo_vpnResList1_key = "nmpo_vpnResList1_key"
let nmpo_vpnResList2_key = "nmpo_vpnResList2_key"
let nmpo_vpnSmartClick_key = "nmpo_vpnSmartClick_key"

extension NMPOManager {
    func nmpo_createDataBase() {
        nmpo_storeManager.loadPersistentStores { _, nmpo_error in
            if nmpo_error == nil {
                let nmpo_serverModels = self.nmpo_getAllServerModels()
                if nmpo_serverModels.count == 0 {
                let nmpo_model = self.nmpo_createServerModel(nmpo_country:"US", nmpo_address: "195.234.82.185", nmpo_password: "KwmurbWXx.DZVBk6", nmpo_port: "1627", nmpo_smart: true)
                    nmpo_model.nmpo_select = true
                    self.nmpo_updateDataModel()
                   
                }
                return
            }
            
        }
        
    }
    func nmpo_updateDataModel() {
        let nmpo_context = nmpo_storeManager.viewContext
        do {
            if nmpo_context.hasChanges {
                try nmpo_context.save()
            }
        } catch {
            debugPrint("\(error)")
        }
    }
    func nmpo_rollBackDataModel() {
        let nmpo_context = nmpo_storeManager.viewContext
        nmpo_context.rollback()
    }
}
//MARK: - nmpo server
extension NMPOManager {
    @discardableResult func nmpo_createServerModel(nmpo_country:String = "", nmpo_address: String = "", nmpo_password: String = "KwmurbWXx.DZVBk6", nmpo_port: String = "1627", nmpo_method: String = "chacha20-ietf-poly1305", nmpo_smart: Bool = false) -> NMPOSerModel {
        let nmpo_context = nmpo_storeManager.viewContext
        let nmpo_serverModel = NSEntityDescription.insertNewObject(forEntityName: "NMPOSerModel",
                                                                   into: nmpo_context) as! NMPOSerModel
        
        nmpo_serverModel.nmpo_address = nmpo_address
        nmpo_serverModel.nmpo_password = nmpo_password
        nmpo_serverModel.nmpo_port = nmpo_port
        nmpo_serverModel.nmpo_method = nmpo_method
        nmpo_serverModel.nmpo_smart = nmpo_smart
        nmpo_serverModel.nmpo_country = nmpo_country
        nmpo_serverModel.nmpo_icon = "nmpo_list_icon"
        nmpo_serverModel.nmpo_date = Date()
        if nmpo_country == "United States" {
            nmpo_serverModel.nmpo_icon = "nmpo_list_us"
        }
        if nmpo_country == "United Kingdom" {
            nmpo_serverModel.nmpo_icon = "nmpo_list_en"
        }
        if nmpo_country == "Canada" {
            nmpo_serverModel.nmpo_icon = "nmpo_list_ca"
        }
        if nmpo_smart {
            nmpo_serverModel.nmpo_icon = "nmpo_home_changeIcon"
            nmpo_serverModel.nmpo_country = "Auto choose"
        }
        if nmpo_context.hasChanges {
            do {
                try nmpo_context.save()
            } catch {
                
            }
        }
        return nmpo_serverModel
    }
    func nmpo_getAllServerModels() -> [NMPOSerModel] {
        let nmpo_context = nmpo_storeManager.viewContext
        let nmpo_serverModel = NSFetchRequest<NMPOSerModel>(entityName: "NMPOSerModel")
        nmpo_serverModel.predicate = NSPredicate(format: "nmpo_smart == false")
        nmpo_serverModel.sortDescriptors = [NSSortDescriptor.init(key: "nmpo_date", ascending: true)]
        do {
            let nmpo_serverModels = try nmpo_context.fetch(nmpo_serverModel)
            return nmpo_serverModels
        } catch {
            
        }
        return [NMPOSerModel]()
    }
    func nmpo_getSmartServerModel() -> NMPOSerModel? {
        let nmpo_context = nmpo_storeManager.viewContext
        let nmpo_serverModel = NSFetchRequest<NMPOSerModel>(entityName: "NMPOSerModel")
        nmpo_serverModel.predicate = NSPredicate(format: "nmpo_smart == true")
        do {
            let nmpo_serverModels = try nmpo_context.fetch(nmpo_serverModel)
            return nmpo_serverModels.first
        } catch {
            
        }
        return nil
    }
    func nmpo_getSelectServerModels() -> [NMPOSerModel] {
        let nmpo_context = nmpo_storeManager.viewContext
        let nmpo_serverModel = NSFetchRequest<NMPOSerModel>(entityName: "NMPOSerModel")
        nmpo_serverModel.predicate = NSPredicate(format: "nmpo_select == true")
        do {
            let nmpo_serverModels = try nmpo_context.fetch(nmpo_serverModel)
            return nmpo_serverModels
        } catch {
            
        }
        return [NMPOSerModel]()
    }
    func nmpo_getSelectServerModel() -> NMPOSerModel? {
        let nmpo_context = nmpo_storeManager.viewContext
        let nmpo_serverModel = NSFetchRequest<NMPOSerModel>(entityName: "NMPOSerModel")
        nmpo_serverModel.predicate = NSPredicate(format: "nmpo_select == true")
        do {
            let nmpo_serverModels = try nmpo_context.fetch(nmpo_serverModel)
            return nmpo_serverModels.first
        } catch {
            
        }
        return nil
    }
    // 批量删除列表的ip 地址
    func nmpo_deleteServeListModels() {
        let nmpo_context = nmpo_storeManager.newBackgroundContext()
        let nmpo_model = NSFetchRequest<NSFetchRequestResult>(entityName: "NMPOSerModel")
        nmpo_model.predicate = NSPredicate(format: "nmpo_smart == false")
        let nmpo_deltes = NSBatchDeleteRequest(fetchRequest: nmpo_model)
        do {
            try nmpo_context.execute(nmpo_deltes)
            if nmpo_context.hasChanges {
                try nmpo_context.save()
            }
        } catch  {
            
        }
    }
    //MARK: - 保存请求数据
    func nmpo_saveVPNRequestModel(nmpo_vpnReqModel: NMPOVPNRequestModel, nmpo_savePath: String = nmpo_vpnResList1_key) {
        try? Disk.save(nmpo_vpnReqModel, to: .caches, as: "\(nmpo_savePath).json")
    }
    func nmpo_getVPNRequestModel(nmpo_savePath: String = nmpo_vpnResList1_key) -> NMPOVPNRequestModel {
        var nmpo_responseString = nmpo_getSrValue(nmpo_key: nmpo_savePath)
        if nmpo_responseString.count < 10 {
            return NMPOVPNRequestModel()
        }
        let startIndex = nmpo_responseString.index(nmpo_responseString.startIndex, offsetBy: 0)
        nmpo_responseString.remove(at: startIndex)
        nmpo_responseString.remove(at: startIndex)
        let endIndex = nmpo_responseString.index(nmpo_responseString.endIndex, offsetBy: -5)
        nmpo_responseString = String(nmpo_responseString[..<endIndex])
        var nmpo_jsonString = MIUAES.miuaesDecrypt(nmpo_responseString, mode: MIUMode.init(1), key: nmpo_vpn_dKey, keySize: MIUKeySizeAES.init(16), iv: nil, padding: MIUCryptorPadding.init(1))
        nmpo_jsonString = nmpo_jsonString.replacingOccurrences(of: "'", with: "\"")
        nmpo_jsonString = nmpo_jsonString.replacingOccurrences(of: "None", with: "null")
        guard let nmpo_model = NMPOVPNRequestModel(JSONString: nmpo_jsonString) else {
            return NMPOVPNRequestModel()
        }
        return nmpo_model
    }
}
